package info.batcloud.fanli.core.item.collection;

import com.ctospace.archit.common.pagination.Paging;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkDgOptimusMaterialRequest;
import com.taobao.api.response.TbkDgOptimusMaterialResponse;
import info.batcloud.fanli.core.dto.CommissionItemFetchDTO;
import info.batcloud.fanli.core.constants.TaobaoClientConstants;
import info.batcloud.fanli.core.enums.CommissionItemStatus;
import info.batcloud.fanli.core.enums.EcomPlat;
import info.batcloud.fanli.core.enums.ItemSelectionType;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.settings.TaobaoUnionSetting;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.text.ParseException;
import java.util.*;
import java.util.function.Consumer;

@Service
public class OptimusMaterialSelectionCollectorSelection extends AbstractItemSelectionCollector<OptimusMaterialContext> {

    private static final Logger logger = LoggerFactory.getLogger(OptimusMaterialSelectionCollectorSelection.class);

    @Inject
    @Qualifier(TaobaoClientConstants.TAOBAO_CLIENT_ITEM_TBK)
    private TaobaoClient taobaoClient;

    @Inject
    private SystemSettingService systemSettingService;

    @Override
    public CollectResult collect(OptimusMaterialContext context, Consumer<Paging<CommissionItemFetchDTO>> pagingConsumer) {
        CollectResult result = new CollectResult();
        TaobaoUnionSetting taobaoUnionSetting = systemSettingService.findActiveSetting(TaobaoUnionSetting.class);
        TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
        req.setPageSize(context.getPageSize() != null ? context.getPageSize() : 100L);
        Long materialId = context.getMaterialId();
        req.setAdzoneId(Long.valueOf(taobaoUnionSetting.getRebateAdzoneId()));
        req.setMaterialId(materialId);
        try {
            int page = context.getStartPage();
            int num = 0;
            while (true) {
                logger.info("查询" + page + "页");
                req.setPageNo(Long.valueOf(page));
                TbkDgOptimusMaterialResponse rsp = taobaoClient.execute(req);
                if (rsp.getResultList() == null) {
                    break;
                }
                List<CommissionItemFetchDTO> list = this.toCommissionItemFetchBO(context, rsp.getResultList());
                Paging<CommissionItemFetchDTO> paging = new Paging<>();
                paging.setResults(list);
                paging.setPage(page);
                paging.setPageSize(context.getPageSize());
                paging.setResults(list);
                pagingConsumer.accept(paging);
                num += rsp.getResultList().size();
                if (rsp.getResultList().size() < 100) {
                    break;
                }
                if (page >= context.getMaxPage()) {
                    break;
                }
                page++;
            }
            logger.info("同步完成");
            result.setSuccess(true);
            result.setTotalNum(num);
        } catch (ApiException e) {
            logger.error("同步失败", e);
            result.setSuccess(false);
            result.setErrMsg(e.getLocalizedMessage());
        }
        return result;
    }

    private List<CommissionItemFetchDTO> toCommissionItemFetchBO(OptimusMaterialContext context, List<TbkDgOptimusMaterialResponse.MapData> mapDataList) {
        List<CommissionItemFetchDTO> dtoList = new ArrayList<>();
        for (TbkDgOptimusMaterialResponse.MapData mapData : mapDataList) {
            CommissionItemFetchDTO dto = new CommissionItemFetchDTO();
            Date now = new Date();
            dto.setListTime(now);
            /**
             * 商品的下架时间为当前的日期+7天，优惠券的下架时间，活动的下架时间取最大者
             * */
            Date delistTime = DateUtils.addDays(now, 7);
            Date couponEndTime;
            if (mapData.getCouponEndTime() != null) {
                try {
                    couponEndTime = DateUtils.parseDate(mapData.getCouponEndTime(), "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss");
                    dto.setCouponStartTime(DateUtils.parseDate(mapData.getCouponStartTime(), "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"));
                    dto.setCouponEndTime(DateUtils.parseDate(mapData.getCouponEndTime(), "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"));
                } catch (ParseException e) {
                    try {
                        couponEndTime = new Date(Long.valueOf(mapData.getCouponEndTime()));
                    } catch (Exception e1) {
                        couponEndTime = delistTime;
                    }
                }
            } else {
                couponEndTime = delistTime;
            }
            dto.setDelistTime(Collections.max(Arrays.asList(delistTime, couponEndTime)));
            dto.setSourceCatId(mapData.getCategoryId());
            dto.setShopTitle(StringUtils.defaultString(mapData.getShopTitle(), ""));
            dto.setCouponRemainCount(mapData.getCouponRemainCount() == null ? null : mapData.getCouponRemainCount().intValue());
            dto.setCouponTotalCount(mapData.getCouponTotalCount() == null ? null : mapData.getCouponTotalCount().intValue());
            dto.setCoupon(mapData.getCouponStartTime() == null ? false : true);
            dto.setCouponValue(Float.valueOf(mapData.getCouponAmount()));
            dto.setSourceItemUrl(mapData.getClickUrl());
            dto.setSourceItemId(mapData.getItemId());
            dto.setTitle(mapData.getTitle());
            dto.setSourceItemClickUrl(mapData.getClickUrl());
            dto.setCouponClickUrl(mapData.getCouponClickUrl());
            dto.setOriginPrice(Float.valueOf(mapData.getZkFinalPrice()));
            float couponStartFee = 0f;
            if (StringUtils.isNotBlank(mapData.getCouponStartFee())) {
                couponStartFee = Float.valueOf(mapData.getCouponStartFee());
            }
            dto.setCouponThresholdAmount(couponStartFee);
            dto.setCommissionRate(Float.valueOf(mapData.getCommissionRate()));
            dto.setEcomPlat(mapData.getUserType() == 0 ? EcomPlat.TAOBAO : EcomPlat.TMALL);
            dto.setImgList(mapData.getSmallImages());
            dto.setPicUrl(mapData.getPictUrl());
            try {
                dto.setSales(mapData.getVolume() == null ? 0 : mapData.getVolume().intValue());
            } catch (Exception e) {
                dto.setSales(0);
            }
            dto.setStatus(CommissionItemStatus.ONSALE);
            dto.setChannelId(context.getChannelId());
            dto.setShopcatId(context.getShopcatId());
            dto.setRecommend(context.isRecommend());
            dtoList.add(dto);
        }
        return dtoList;
    }

    @Override
    public Class<OptimusMaterialContext> getContextType() {
        return OptimusMaterialContext.class;
    }

    @Override
    protected ItemSelectionType getItemSelectionType() {
        return ItemSelectionType.OPTIMUS_MATERIAL;
    }
}
